//
//  YHPictureSelectorViewController.swift
//  YHWeibo
//
//  Created by 昱含 on 16/5/29.
//  Copyright © 2016年 YuHan. All rights reserved.
//

import UIKit
import HMImagePicker

private let reuseIdentifier = "Cell"
private let colCount: CGFloat = 4
private let margin: CGFloat = 3
private let imageCount: Int = 9
private let itemWidth: CGFloat = (screenWidth - (colCount + 1) * margin) / colCount
class YHPictureSelectorViewController: UICollectionViewController {
    
    lazy var images :[UIImage] = [UIImage]()
    lazy var selectedAsset: [PHAsset] = [PHAsset]()
    
    init(){
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        super.init(collectionViewLayout:layout)
        self.collectionView!.registerClass(YHPictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView?.backgroundColor = UIColor.whiteColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()


    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let delta = images.count == imageCount ? 0 : 1
        return images.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! YHPictureSelectorCell
        if indexPath.item == images.count {
            cell.image = nil
        }else{
            cell.image = images[indexPath.item]
        }
    
        cell.backgroundColor = randomColor()
        
        cell.pictureSelectorDelegate = self
    
        return cell
    }
}

extension YHPictureSelectorViewController: YHPictureSelectorViewControllerDelegate{
    
    func addPicture() {
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
            print("没有访问权限")
            return
        }
        let picker = HMImagePickerController(selectedAssets: selectedAsset)
        picker.pickerDelegate = self
        picker.targetSize = CGSize(width: 600, height: 600)
        picker.maxPickerCount = imageCount
        self.presentViewController(picker, animated: true, completion: nil)

    }
    
    func deletePicture(cell: YHPictureSelectorCell) {
        print("删除照片")
        guard let indexPath = collectionView?.indexPathForCell(cell) else{
            return
        }
        images.removeAtIndex(indexPath.item)
        selectedAsset.removeAtIndex(indexPath.item)
        collectionView?.reloadData()
    }
}

@objc protocol YHPictureSelectorViewControllerDelegate: NSObjectProtocol{
    
    optional func addPicture()
    optional func deletePicture(cell: YHPictureSelectorCell)
}


extension YHPictureSelectorViewController: HMImagePickerControllerDelegate{
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        self.images = images
        self.selectedAsset = selectedAssets!
        self.collectionView?.reloadData()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

class YHPictureSelectorCell: UICollectionViewCell {
    
    var image : UIImage? {
        didSet{
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    weak var pictureSelectorDelegate: YHPictureSelectorViewControllerDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: #selector(YHPictureSelectorCell.addBtnClick), forControlEvents: .TouchUpInside)
        
        deleteBtn.addTarget(self, action: #selector(YHPictureSelectorCell.deleteBtnClick), forControlEvents: .TouchUpInside)
    }
    
    @objc private func addBtnClick() {
        print(#function)
        pictureSelectorDelegate?.addPicture?()
    }
    
    @objc private func deleteBtnClick() {
        pictureSelectorDelegate?.deletePicture?(self)
    }
    
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_photo_close"), forState: .Normal)
        return btn
    }()
    
    private lazy var addBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_pic_add"), forState: .Normal)
        btn.imageView?.contentMode = .ScaleAspectFill
        //TODO: - clip
        btn.imageView?.clipsToBounds = true
        return btn
    }()
    
}
